/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-gateway-open
*
* @File name : AccessFilter.java
*
* @Author : Administrator
*
* @Date : 2017年8月7日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年8月7日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.gateway.api.filter;


import java.security.NoSuchAlgorithmException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.marketing.common.util.CommonUtils;
import org.marketing.common.util.MapConverUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.yonyou.gmmc.gateway.api.util.IdrealerStatus;

/**
 * @author Administrator TODO description
 * @date 2017年8月7日
 */
@Service
public class AccessFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(AccessFilter.class);


    @Value("${SECRET_KEY_STATUS}")
    private String key;
    
    @Override
    public Object run() {
        log.info("------进入gateway------");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        HttpServletResponse res = ctx.getResponse();
        Map<String,Object> map = MapConverUtil.RequestPO2Map(request, new IdrealerStatus());
//        try {
//            param = GetRequestJsonUtils.getRequestJsonString(request);
//        } catch (IOException e) {
//            log.error(e.getMessage());
//        }
//        log.info("传入的参数为：" + param);
        if (!check(map)) {
            log.warn("---sign not pass");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(505);
            return null;
        }

        // ctx.getResponse().addHeader("Access-Control-Allow-Credentials", "true");
        // ctx.getResponse().addHeader("Access-Control-Allow-Origin", "*");
        // ctx.getResponse().addHeader("Access-Control-Allow-Methods", "OPTIONS,HEAD,GET,PUT,POST,DELETE,PATCH");
        return null;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 获取登录用户远程主机ip地址
     * 
     * @param request
     * @return
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
    public boolean check(Map<String,Object> map) {
        log.info("key为："+key);
        log.info("移除sign前的map为》"+map);
        String sign = map.get("sign").toString();
        log.info("获取的sign》》》"+sign);
        map.remove("sign");
        log.info("移除sign后的map为》"+map);
        try {
            Map<String,Object> param = CommonUtils.generateSign(map, key);
            String s = param.get("sign").toString();
            log.info("生成的sign》》》"+s);
            if(sign.equals(s)){
                return true;
            }else{
                return false;
            }
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

}
